<!-- AMap.PlaceSearch + jquery.twbsPagination -->
<!doctype html>
<html lang="zh-CN">

<head>
    <!-- 原始地址：http://webapi.amap.com/ui/1.0/ui/misc/MarkerList/examples/pagination.html -->
    <base href="http://webapi.amap.com/ui/1.0/ui/misc/MarkerList/examples/" />
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>收货地址定位</title>
    <link rel="stylesheet" type="text/css" href="./index.css">
    <link rel="stylesheet" type="text/css" href="http://a.amap.com/amap-ui/static/1.0/ui/misc/MarkerList/examples/pagination.css">
    <style>
#keywords {
    position: absolute;
    left: 50%;
    top: 7px;
    line-height: 200%;
    padding: 0 5px;
    font-size: 13px;
    border-radius: 3px;
    border: 1px solid #ccc;
    width: 200px;
    margin-left: -108px;
}
#container {
    height: 50%;
    width: 100%;
}
#outer-box{
	padding-right: 0;
}
#panel{
	position: relative;
	width: 100%;
	height:50%;
}
.pagination {
    padding-left: 100px;
}
        #certain{
            position: absolute;
            left: 50%;
            top: 8px;
            line-height: 27px;
            padding: 0 5px;
            font-size: 12px;
            border-radius: 0 3px 3px 0;
            background: #ce3f37;
            height: 27px;
            color: #fff;
            margin-left: 100px;
        }
.back{
    position: absolute;
    background: url("http://xgc.chinaddcat.com/m/phoneImg/back.png") no-repeat 0 0;
    background-size: 14px 21px;
    width: 10px;
    height: 21px;
    left:20px;
    top:10px;
}
 </style>
</head>

<body>
    <div id="outer-box">
        <div id="container" tabindex="0"></div>
        <a class="back" href="javascript:history.back(-1)"></a><input type="text" id="keywords" value="" /><a id="certain">确定</a>
        <div id="panel" class="scrollbar1">
            
            <ul id="myList"/></ul>
			<ul id="pagination-demo" class="pagination-sm"/>
        </div>
    </div>

    <script type="text/javascript" src="http://webapi.amap.com/ui/1.0/plug/ext/jquery-1.12.4.min.js?v=1.0.11"></script>
    <script type="text/javascript" src="http://a.amap.com/amap-ui/static/1.0/ui/misc/MarkerList/examples/jquery.twbsPagination.min.js?v=1.0.11"></script>
    <script type="text/javascript" src='http://webapi.amap.com/maps?v=1.4.0&key=92a30c82eb21689506c1d726f7425dc9'></script>
    <!-- UI组件库 1.0 -->
    <script src="http://webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>
    <script type="text/javascript">

        AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
            var autoOptions = {
                city: "", //城市，默认全国
                input: "keywords"//使用联想输入的input的id
            };
            autocomplete= new AMap.Autocomplete(autoOptions);
            var placeSearch = new AMap.PlaceSearch({
                city:'',
                map:map
            });
            AMap.event.addListener(autocomplete, "select", function(e){
                //TODO 针对选中的poi实现自己的功能
                var eThis = e;
                e.formattedAddress=e.poi.name;
                onComplete(e)
                document.getElementById('certain').onclick=function () {
                    setItem('location',e.poi.location.lat+","+e.poi.location.lng);
                    setItem('save_add_city',e.poi.district);
                    setItem('save_add_detail',e.poi.name);
                    setItem('ifAdd','false');
                    history.back();
                }
            });
        });
        function setItem(name,value){
            var exp = new Date();
            exp.setTime(exp.getTime()+1000*60*60*24*15);
            //document.cookie=name+"="+escape(value)+";";
            document.cookie= name + "="+escape(value)+";expires="+exp.toGMTString() + ";";
        }
        //创建地图
    var map = new AMap.Map('container', {
        zoom: 9,
		resizeEnable: true
    });

	map.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition:'RB'
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    });
    //解析定位结果
    function onComplete(data) {
       
		//console.log(data.formattedAddress+":***"+data.position.getLng()+","+data.position.getLat());
		document.getElementById('keywords').value=data.formattedAddress;
        document.getElementById('certain').onclick=function () {
            setItem('location',data.position.getLng()+","+data.position.getLat());
            setItem('save_add_city',data.addressComponent.province+data.addressComponent.city+data.addressComponent.district);
            setItem('save_add_detail',data.addressComponent.township+data.addressComponent.neighborhood+data.addressComponent.building);
            setItem('ifAdd','false');
            //history.back();
            window.location.replace(document.referrer)
            //window.location.href=history.go(-1);
        }

		   AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
        function(MarkerList, SimpleMarker, SimpleInfoWindow) {

            //即jQuery/Zepto
            var $ = MarkerList.utils.$;

            var defaultIconStyle = function(index) {
                    return 'red-' + (index + 1);
                }, //默认的图标样式
                hoverIconStyle = function(index) {
                    return 'blue-' + (index + 1);
                }, //鼠标hover时的样式
                selectedIconStyle = function(index) {
                    return 'blue-' + (index + 1);
                } //选中时的图标样式
            ;



            var markerList = new MarkerList({
                map: map,
                //ListElement对应的父节点或者ID
                listContainer: "myList", //document.getElementById("myList"),
                //选中后显示

                //从数据中读取位置, 返回lngLat
                getPosition: function(item) {
                    return item.location;
                },
                //数据ID，如果不提供，默认使用数组索引，即index
                getDataId: function(item, index) {

                    return item.id;
                },
                getInfoWindow: function(data, context, recycledInfoWindow) {

                    if (recycledInfoWindow) {

                        recycledInfoWindow.setInfoTitle(data.name);
                        recycledInfoWindow.setInfoBody(data.address);

                        return recycledInfoWindow;
                    }

                    return new SimpleInfoWindow({
                        infoTitle: data.name,
                        infoBody: data.address,
                        offset: new AMap.Pixel(0, -32)
                    });
                },
                //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
                getMarker: function(data, context, recycledMarker) {

                    if (recycledMarker) {
                        recycledMarker.setIconStyle(defaultIconStyle(context.index));
                        return;
                    }

                    return new SimpleMarker({
                        iconTheme: 'numv1',
                        containerClassNames: 'my-marker',
                        iconStyle: defaultIconStyle(context.index),
                    });
                },
                //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
                getListElement: function(data, context, recycledListElement) {

                    var label = '' + (context.index + 1);

                    //使用模板创建
                    $('#myList').empty();
                    var innerHTML = MarkerList.utils.template(
                        '<% if(data.photos && data.photos[0]) { %>' +
                        '<div class="poi-imgbox">' +
                        '    <span class="poi-img" style="background-image:url(<%- data.photos[0].url %>)"></span>' +
                        '</div>' +
                        '<% } %>' +
                        '<div class="poi-info-left">' +
                        '    <h3 class="poi-title">' +
                        '        <%- label %>. <%- data.name %>' +
                        '    </h3>' +
                        '    <div class="poi-info">' +
                        '        <p class="poi-addr">地址：<%- data.address %></p>' +
                        '<% if(data.tel ){ %>' +
                        '        <p class="poi-addr">电话：<%- data.tel %></p>' +
                        '<% } %>' +
                        '    </div>' +
                        '</div>' +
                        '<div class="clear"></div>', {
                            data: data,
                            label: label
                        });

                    if (recycledListElement) {
                        recycledListElement.innerHTML = innerHTML;
                        return recycledListElement;
                    }

                    return '<li class="poibox">' +
                        innerHTML +
                        '</li>';
                },
                //列表节点上监听的事件
                listElementEvents: ['click', 'mouseenter', 'mouseleave'],
                //marker上监听的事件
                markerEvents: ['click', 'mouseover', 'mouseout'],
                //makeSelectedEvents:false,
                selectedClassNames: 'selected',
                autoSetFitView: true
            });

            window.markerList = markerList;

            AMap.plugin(["AMap.PlaceSearch"], function() {

                var placeSearch = new AMap.PlaceSearch({ //构造地点查询类
                    pageSize: 10,
                    pageIndex: 1,
                    extensions: 'all',
                });

                var $pagination = $('#pagination-demo');

                function initPagination(page, totalPages) {

                    //初始化分页器
                    $pagination.twbsPagination({
                        totalPages: totalPages,
                        startPage: page,
                        prev: null,
                        first: '首页',
                        next: '下一页',
                        last: null,
                        initiateStartPageClick: false,
                        onPageClick: function(event, page) {
                            goPage(page);
                        }
                    });
                }

                var inited = false;

                var $keywords = $('#keywords');

                function goPage(page) {

                    //设置当前页
                    placeSearch.setPageIndex(page);
                    //关键字查询
                    placeSearch.search($keywords.val(), function(status, result) {

                        if (status !== 'complete') {
                            alert('返回数据出错!');
                        }

                        //render当前页的数据
                        markerList.render(result.poiList.pois);

                        if (!inited) {
                            inited = true;
                            //首次初始化
                            initPagination(page, Math.ceil(result.poiList.count / result.poiList.pageSize));
                        }

                    });
                }

                goPage(1);

                $keywords.on('keypress', function(e) {
                    if (e.which === 13) {
                        inited = false;
                        $pagination.twbsPagination('destroy');
                        goPage(1);
                    }
                });
            });

            markerList.on('selectedChanged', function(event, info) {

                if (info.selected) {

                    if (info.selected.marker) {
                        //更新为选中样式
                        info.selected.marker.setIconStyle(selectedIconStyle(info.selected.index));
                    }
                }

                if (info.unSelected && info.unSelected.marker) {
                    //更新为默认样式
                    info.unSelected.marker.setIconStyle(defaultIconStyle(info.unSelected.index));
                }
            });


            markerList.on('listElementMouseenter markerMouseover', function(event, record) {

                if (record && record.marker) {
                    //非选中的id
                    if (!this.isSelectedDataId(record.id)) {
                        //设置为hover样式
                        var data=record.data;
                        record.marker.setIconStyle(hoverIconStyle(record.index));
                        var location = data.location.lng+","+data.location.lat;
                        setItem('location',location);
                        setItem('save_add_city',data.pname+data.cityname+data.adname);
                        setItem('save_add_detail',data.address+data.name);
                        setItem('ifAdd','false');
                        window.location.replace(document.referrer)
                        //history.back();
                        //this.closeInfoWindow();
                    }
                }
            });

            markerList.on('listElementMouseleave markerMouseout', function(event, record) {

                if (record && record.marker) {

                    if (!this.isSelectedDataId(record.id)) {
                        //恢复默认样式
                        record.marker.setIconStyle(defaultIconStyle(record.index));
                    }
                }
            });


        });

    }
    //解析定位错误信息
    function onError(data) {
        alert("定位失败！");
    }
        function getItem(name){
            var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
            if (arr != null) return unescape(arr[2]); return null;
        }
	
 
    </script>
</body>

</html>